/*
       Licensed to the Apache Software Foundation (ASF) under one
       or more contributor license agreements.  See the NOTICE file
       distributed with this work for additional information
       regarding copyright ownership.  The ASF licenses this file
       to you under the Apache License, Version 2.0 (the
       "License"); you may not use this file except in compliance
       with the License.  You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

       Unless required by applicable law or agreed to in writing,
       software distributed under the License is distributed on an
       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
       KIND, either express or implied.  See the License for the
       specific language governing permissions and limitations
       under the License.
 */

package com.leqicheng.tenon;

import java.net.URI;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.cordova.CordovaActivity;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import org.json.JSONArray;
import org.json.JSONException;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.WindowManager;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.leqicheng.tenon.login.ChannelLoginHttpRequest;
import com.leqicheng.tenon.login.GameInfoHttpRequest;
import com.leqicheng.tenon.login.PopLoginWindow;
import com.leqicheng.tenon.login.weibo.WeiboConstants;
import com.leqicheng.tenon.model.EntryInfoModel;
import com.leqicheng.tenon.pay.PopPayWindow;
import com.leqicheng.tenon.share.PopShareWindow;
import com.leqicheng.tenon.shortUrl.ShortUrlHttpRequest;
import com.leqicheng.tenon.shortUrl.ShortUrlWindow;
import com.leqicheng.tenon.updata.UpdataHttpRequest;
import com.leqicheng.tenon.util.ContextProvider;
import com.leqicheng.tenon.util.GeneralCallBack;
import com.leqicheng.tenon.util.GetTimeDiffrenceRequest;
import com.leqicheng.tenon.util.MenuButton;
import com.leqicheng.tenon.util.NetworkUtil;
import com.leqicheng.tenon.util.RequestStatus;
import com.leqicheng.tenon.util.RequestTypeEnum;
import com.leqicheng.tenon.util.SendShortCutUtil;
import com.leqicheng.tenon.util.TenonDB;
import com.leqicheng.tenon.util.VersionManagerUtil;
import com.leqicheng.tenon.util.WindowStatusCode;
import com.leqicheng.tenon.util.MenuButton.OnChooseListener;
import com.sina.weibo.sdk.api.share.BaseResponse;
import com.sina.weibo.sdk.api.share.IWeiboHandler.Response;
import com.sina.weibo.sdk.api.share.IWeiboShareAPI;
import com.sina.weibo.sdk.api.share.WeiboShareSDK;
import com.sina.weibo.sdk.auth.sso.SsoHandler;
import com.sina.weibo.sdk.constant.WBConstants;
import com.tencent.smtt.sdk.QbSdk;
import com.umeng.analytics.MobclickAgent;

public class RuntimeActivity extends CordovaActivity implements GeneralCallBack,
        Response, OnFocusChangeListener {

    public static SsoHandler mSsoHandler;
    private MenuButton buttonView;
    private Context mContext;
    private String mGameUrl;
    private int mScreenWidth;
    private int mScreenHeight;
    private TenonDB mTenonDB;
    private EntryInfoModel mEntryInfoModel;
    private long mExitTime = 0;
    private IWeiboShareAPI mWeiboShareAPI;
    private PopShareWindow mPopShareWindow;
    private PopupWindow mPopupWindow;
    public static boolean isForeground = false;

    private Handler mWindowHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == WindowStatusCode.LOGIN_WINDOW_SUCCEED) {
                if (msg.arg1 == 1) {
                    Map<String, Object> resultMap = (Map<String, Object>) msg.obj;
                    getEgretGameUrl();
                }
                mPopupWindow.dismiss();
            } else if (msg.what == WindowStatusCode.PAY_WINDOW_SUCCEED) {
                mPopupWindow.dismiss();
                LoadUrlAndAddView();
            } else if (msg.what == WindowStatusCode.SHARE_WINDOW_SUCCEED) {
                mPopupWindow.dismiss();
            } else if (msg.what == WindowStatusCode.INIT) {
                mPopupWindow.dismiss();
            }
        }
    };

    private Bundle mPastBundle;
    private Bundle mNewBundle;
    private boolean mCanSendShortIconByPush = false;
    private PopLoginWindow mPopLoginWindow;
    private BroadcastReceiver restartBroadcastReceiver;
    private PopPayWindow mPopPayWindow;
    private BroadcastReceiver mEgretBroadcastReceiver;
    private BroadcastReceiver reloadBroadcastReceiver;
    private BroadcastReceiver nowUrlBroadcastReceiver;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        mEntryInfoModel = EntryInfoModel.getInstance();
        ContextProvider.initIfNotInited(this.getApplicationContext());
        GetTimeDiffrenceRequest getTimeDiffrenceRequest = new GetTimeDiffrenceRequest(
                mContext, this);
        getTimeDiffrenceRequest.AsyncHttpClientGetOnBack();
        // 发包修改---------------------------------------------------------------
        initFirstGame();
        // --------------------------------------------------------------------
        this.mTenonDB = new TenonDB(mContext);
        if (getIntent() != null) {
            if ("start_tenon".equals(getIntent().getAction())) {
                if (getIntent().getExtras() != null) {
                    mPastBundle = getIntent().getExtras();
                    putBundle(mPastBundle);
                }
            }
        }
        registerRestartBroadcast();
        registerReloadBroadcast();
        this.getWindow().addFlags(
                WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        this.buttonView = new MenuButton(this, new OnChooseListener() {

            @Override
            public void chooseBack(int index) {
                switch (index) {
                case 1:
                    finish();
                    break;
                case 2:
                    EntryInfoModel model = EntryInfoModel.getInstance();
                    SendShortCutUtil.addShortcutToDesktop(
                            RuntimeActivity.this.mContext, model.getGameName(),
                            model.getGameIconUrl(), model.getGameId(),
                            model.getChannelId(), model.getTenonUserId());
                    break;
                case 3:
                    handleShare(null);
                    break;
                case 4:
                    Intent intent = new Intent();
                    intent.setAction("reload_game");
                    mContext.sendBroadcast(intent);
                    break;
                case 5:
                    String lastUrl = appView.getUrl();
                    mEntryInfoModel.setGameLastUrl(lastUrl);
                    sendShortUrlRequest();
                    break;
                default:
                    break;
                }
            }
        });

        GameInfoHttpRequest gameUrlHttpRequest = new GameInfoHttpRequest(
                mContext, this);
        gameUrlHttpRequest.postRequest(mEntryInfoModel);
        try {
            // mWeiboShareAPI = WeiboShareSDK.createWeiboAPI(this,
            // WeiboConstants.APP_KEY);
            // mWeiboShareAPI.registerApp(); // 将应用注册到微博客户端
        } catch (Exception e) {
        }
    }
    
    private void sendShortUrlRequest() {
        ShortUrlHttpRequest shortUrlHttpRequest = new ShortUrlHttpRequest(
                mContext, this);
        shortUrlHttpRequest.postRequest(mEntryInfoModel);
    }

    private void initFirstGame() {
        mEntryInfoModel.setChannelId("tenon");
        mEntryInfoModel.setGameId("8dcd2b7d-06d8-471d-8c53-fa9b7a99087f");
        Bundle firstBundle = new Bundle();
        firstBundle.putString("game_key", mEntryInfoModel.getGameId());
        firstBundle.putString("channel_key", mEntryInfoModel.getChannelId());
        mPastBundle = firstBundle;
    }

    private void registerRestartBroadcast() {
        IntentFilter intentFilter = new IntentFilter();

        intentFilter.addAction("restart"); // 为BroadcastReceiver指定action，即要监听的消息名字。

        restartBroadcastReceiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                mContext.unregisterReceiver(this);
                Intent mStartActivity = new Intent(mContext,
                        mContext.getClass());
                mStartActivity.setAction("start_tenon");
                if (mPastBundle != null) {
                    mStartActivity.putExtras(mPastBundle);
                }
                int mPendingIntentId = 123456;
                PendingIntent mPendingIntent = PendingIntent.getActivity(
                        mContext, mPendingIntentId, mStartActivity,
                        PendingIntent.FLAG_CANCEL_CURRENT);
                AlarmManager mgr = (AlarmManager) mContext
                        .getSystemService(Context.ALARM_SERVICE);
                mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100,
                        mPendingIntent);
                System.exit(0);
            }
        };
        mContext.registerReceiver(restartBroadcastReceiver, intentFilter); // 注册监听
    }

    private void registerReloadBroadcast() {
        IntentFilter intentFilter = new IntentFilter();

        intentFilter.addAction("reload_game"); // 为BroadcastReceiver指定action，即要监听的消息名字。

        reloadBroadcastReceiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                LoadUrlAndAddView();
            }
        };
        mContext.registerReceiver(reloadBroadcastReceiver, intentFilter); // 注册监听
    }

    private void putBundle(Bundle bundle) {
        mEntryInfoModel.setChannelId(bundle.getString("channel_key"));
        mEntryInfoModel.setGameId(bundle.getString("game_key"));
        mEntryInfoModel.setGameIconUrl(bundle.getString("game_icon_url"));
        if (bundle.getString("send_short_icon") != null) {
            mCanSendShortIconByPush = true;
        }
        if (bundle.getString("tenon_id") != null) {
            mEntryInfoModel.setTenonUserId(bundle.getString("tenon_id"));
        }
        if (bundle.getString("ChannelUserId") != null) {
            mEntryInfoModel.setOpenId(bundle.getString("ChannelUserId"));
            ChannelLoginHttpRequest channelLoginHttpRequest = new ChannelLoginHttpRequest(
                    mContext, this);
            channelLoginHttpRequest.postRequest(mEntryInfoModel);
        }
    }

    @Override
    protected void onResume() {
        if (mPopupWindow != null && mPopupWindow.isShowing()) {
            mPopupWindow.dismiss();// 关闭
        }
        onWindowFocusChanged(true);
        if (appView != null) {
            appView.getEngine().OnResume();
        }
        MobclickAgent.onResume(this);
        super.onResume();
    }

    @Override
    protected void onPause() {
        if (mPopupWindow != null) {
            mPopupWindow.dismiss();
        }
        if (appView != null) {
            appView.getEngine().OnPause();
        }
        MobclickAgent.onPause(this);
        super.onPause();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode,
            Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        if (mSsoHandler != null) {
            mSsoHandler.authorizeCallBack(requestCode, resultCode, intent);
        }
    }

    public void loadGame(String url) {
        this.mGameUrl = url;
        if (!QbSdk.isTbsCoreInited()) {// preinit只需要调用一次，如果已经完成了初始化，那么就直接构造view
            QbSdk.preInit(this, new MyPreInitCallback());// 设置X5初始化完成的回调接口
        } else {
            LoadUrlAndAddView();
        }

    }

    private class MyPreInitCallback implements QbSdk.PreInitCallback {
        public void onCoreInitFinished() {

        };

        @Override
        public void onViewInitFinished() {
            LoadUrlAndAddView();
        }
    }

    private void LoadUrlAndAddView() {
        if (buttonView != null) {
            if (root != null) {
                root.removeAllViews();
            }
        }
        // 清空buttonView 小圆点
        if (this.appView != null) {
            appView.handleDestroy();
            appView = null;
        }
        RuntimeActivity.this.loadUrl(RuntimeActivity.this.mGameUrl);
        Log.i("MainActivity", "loadUrl:" + mGameUrl);
        root.addView(RuntimeActivity.this.buttonView);
        root.getViewTreeObserver().addOnGlobalLayoutListener(
                new OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        setImmersiveMode();
                    }
                });
    }

    @SuppressLint("NewApi")
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        setImmersiveMode();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        DisplayMetrics dm = this.getResources().getDisplayMetrics();
        this.mScreenWidth = dm.widthPixels;
        this.mScreenHeight = dm.heightPixels;
        buttonView.setWindowParams(mScreenWidth, mScreenHeight);
    }

    @Override
    public void onComplete(RequestTypeEnum requestType, int status,
            String responseBody) {
        switch (status) {
        case RequestStatus.NETWORK_ERROR:
            Toast.makeText(mContext, "网络错误", Toast.LENGTH_SHORT).show();
            break;
        case RequestStatus.OBTAIN_SUCCESS:
            switch (requestType) {
            case LOGIN:
                ProcessingLoginData(responseBody);
                break;
            case GET_GAME_URL:
                processingGameData(responseBody);
                whetherNeedDeskTop();
                processingScreenOrientation(responseBody);
                if (mEntryInfoModel.isEgretGame()) {
                    Toast.makeText(mContext,
                            "请登录后开始玩" + mEntryInfoModel.getGameName(),
                            Toast.LENGTH_SHORT).show();
                    registerEgretPayBroadcast();
                    handleLogin();
                } else {
                    loadGame(mEntryInfoModel.getGameUrl());
                }
                whetherNeedUpdata();
                break;
            case GET_EGRET_GAME_URL:
                processingEgretGameUrl(responseBody);
                loadGame(mEntryInfoModel.getGameEgretUrl());
                break;
            case UPDATA:
                String UpdataVersion = JSON.parseObject(responseBody)
                        .getString("version_id");
                String UpdataApkUrl = JSON.parseObject(responseBody).getString(
                        "address_url");
                try {
                    if (!UpdataVersion.equals(VersionManagerUtil
                            .getVersionName(mContext))) {
                        new UpdataApk(mContext, UpdataVersion, UpdataApkUrl);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case GET_SHORT_URL:
                String tinyUrl = JSON.parseObject(responseBody).getString("tinyurl");
                ShortUrlWindow shortUrlWindow = new ShortUrlWindow(mContext, tinyUrl);
                PopupWindow shortUrlPopWindow = shortUrlWindow.getPopupWindow();
                if (shortUrlPopWindow != null && shortUrlPopWindow.isShowing()) {
                    shortUrlPopWindow.dismiss();// 关闭
                    shortUrlWindow = null;
                    shortUrlPopWindow = null;
                } else {
                    shortUrlPopWindow.showAtLocation(this.getWindow()
                            .getDecorView(), Gravity.CENTER, 0, 0);
                }
                break;
            default:
                break;
            }
            break;
        default:
            switch (requestType) {
            case GET_LOG_ID:
                break;
            default:
                Toast.makeText(mContext, "服务器错误，请重试。", Toast.LENGTH_SHORT)
                        .show();
                break;
            }
            break;
        }
    }

    private void registerEgretPayBroadcast() {
        IntentFilter intentFilter = new IntentFilter();

        intentFilter.addAction("egret_pay"); // 为BroadcastReceiver指定action，即要监听的消息名字。

        mEgretBroadcastReceiver = new BroadcastReceiver() {

            @SuppressWarnings("deprecation")
            @Override
            public void onReceive(Context context, Intent intent) {
                String egretUrlInString = intent
                        .getStringExtra("egret_url_params");
                String[] egretUrlPart = egretUrlInString.split("[?]");
                String[] urlParams = egretUrlPart[1].split("&");
                Map<String, String> dataMap = new HashMap<String, String>();
                for (String eachUrlParams : urlParams) {
                    String[] eachUrlParamsItem = eachUrlParams.split("=");
                    if (eachUrlParamsItem.length == 2) {
                        dataMap.put(eachUrlParamsItem[0], eachUrlParamsItem[1]);
                    }
                }
                org.json.JSONObject dataJsonObject = new org.json.JSONObject(
                        dataMap);
                JSONArray egretPayData = new JSONArray();
                egretPayData.put(dataJsonObject);
                handlePay(egretPayData);
            }
        };
        mContext.registerReceiver(mEgretBroadcastReceiver, intentFilter); // 注册监听
    }

    private void processingEgretGameUrl(String responseBody) {
        String egretGameUrl = JSON.parseObject(responseBody).getString(
                "egret_game_url");
        mEntryInfoModel.setGameEgretUrl(egretGameUrl);
    }

    private void whetherNeedUpdata() {
        if (NetworkUtil.isWIFI()) {
            UpdataHttpRequest updataHttpRequest = new UpdataHttpRequest(
                    mContext, this);
            updataHttpRequest.postRequest(mEntryInfoModel);
        }
    }

    private void processingScreenOrientation(String responseBody) {
        String Orientation = JSON.parseObject(responseBody).getString(
                "orientation");
        if (Orientation.equals("0")) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        } else if (Orientation.equals("1")) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
        buttonView.initOrientation();
    }

    private void whetherNeedDeskTop() {
        if (mCanSendShortIconByPush) {
            SendShortCutUtil.addShortcutToDesktop(mContext,
                    mEntryInfoModel.getGameName(),
                    mEntryInfoModel.getGameIconUrl(),
                    mEntryInfoModel.getGameId(),
                    mEntryInfoModel.getChannelId(),
                    mEntryInfoModel.getTenonUserId());
            mCanSendShortIconByPush = false;
        }
    }

    private void processingGameData(String responseBody) {
        String isEgret = JSON.parseObject(responseBody).getString("is_egret");
        String GameUrl = JSON.parseObject(responseBody).getString("game_url");
        String GameIconUrl = JSON.parseObject(responseBody).getString(
                "icon_url");
        String GameName = JSON.parseObject(responseBody).getString("name");
        String ChannelName = JSON.parseObject(responseBody).getString(
                "channel_name");
        String ShareUrl = JSON.parseObject(responseBody).getString("share_url");
        if ("1".equals(isEgret)) {
            mEntryInfoModel.setEgretGame(true);
        } else {
            mEntryInfoModel.setEgretGame(false);
        }
        mEntryInfoModel.setShareUrl(ShareUrl);
        mEntryInfoModel.setGameUrl(GameUrl);
        mEntryInfoModel.setGameIconUrl(GameIconUrl);
        mEntryInfoModel.setGameName(GameName);
        mEntryInfoModel.setChannelName(ChannelName);

    }

    private void ProcessingLoginData(String responseBody) {
        String TenonUserId = JSON.parseObject(responseBody)
                .getString("user_id");
        String TenonUserName = JSON.parseObject(responseBody).getString("name");
        String TenonUserIconUrl = JSON.parseObject(responseBody).getString(
                "image_url");
        String TenonUserSex = JSON.parseObject(responseBody).getString("sex");
        mEntryInfoModel.setTenonUserId(TenonUserId);
        mEntryInfoModel.setTenonUserName(TenonUserName);
        mEntryInfoModel.setTenonUserIconUrl(TenonUserIconUrl);
        mEntryInfoModel.setTenonUserSex(TenonUserSex);
        this.mTenonDB = new TenonDB(mContext);
        mTenonDB.insert(TenonUserId, mEntryInfoModel.getChannelId(),
                mEntryInfoModel.getGameId(),
                mEntryInfoModel.getTenonUserName(),
                mEntryInfoModel.getTenonUserIconUrl(),
                mEntryInfoModel.getTenonUserSex());
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            this.exit();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void exit() {
        if ((System.currentTimeMillis() - this.mExitTime) > 2000) {
            Toast.makeText(this.getApplicationContext(), "再按一次退出程序",
                    Toast.LENGTH_SHORT).show();
            this.mExitTime = System.currentTimeMillis();
        } else {
            this.finish();
        }
    }

    /**
     * @see {@link Activity#onNewIntent}
     */
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        mNewBundle = intent.getExtras();
        if (intent.getAction() != null
                && intent.getAction().equals("start_tenon")) {
            if (intent.getExtras() != null) {
                if (!(mEntryInfoModel.getGameId().equals(
                        mNewBundle.getString("game_key")) && mEntryInfoModel
                        .getChannelId().equals(
                                mNewBundle.getString("channel_key")))) {
                    mPastBundle = mNewBundle;
                    reLoadGame();
                }
            }
        }
        if (intent.getAction().equals(
                "com.sina.weibo.sdk.action.ACTION_SDK_REQ_ACTIVITY")) {
            if (mWeiboShareAPI != null) {
                mWeiboShareAPI.handleWeiboResponse(intent, this);
            }
        }
    }

    public void reLoadGame() {
        initRuntime();
        // 重新填充数据
        putBundle(mPastBundle);
        GameInfoHttpRequest gameInfoHttpRequest = new GameInfoHttpRequest(
                mContext, this);
        gameInfoHttpRequest.postRequest(mEntryInfoModel);
    }

    private void initRuntime() {
        mEntryInfoModel.init();
        // 重新获取timediffrence
        GetTimeDiffrenceRequest getTimeDiffrenceRequest = new GetTimeDiffrenceRequest(
                mContext, this);
        getTimeDiffrenceRequest.AsyncHttpClientGetOnBack();
        // 清空popwindows
        if (TenonPlugin.hasRegister) {
            Intent initIntent = new Intent();
            initIntent.setAction("tenon init");
            mContext.sendBroadcast(initIntent);
        }
    }

    /**
     * 接收微客户端博请求的数据。
     * 当微博客户端唤起当前应用并进行分享时，该方法被调用。
     * @param baseRequest
     *            微博请求数据对象
     * @see {@link IWeiboShareAPI#handleWeiboRequest}
     */
    @Override
    public void onResponse(BaseResponse baseResp) {
        if (mPopupWindow != null) {
            mPopupWindow.dismiss();
        }
        Intent intent = new Intent();
        switch (baseResp.errCode) {
        case WBConstants.ErrorCode.ERR_OK:
            Toast.makeText(mContext, "分享成功", Toast.LENGTH_LONG).show();
            intent.putExtra("share_status", true);
            intent.setAction("weibo share complete");
            mContext.sendBroadcast(intent);
            break;
        case WBConstants.ErrorCode.ERR_CANCEL:
            Toast.makeText(mContext, "取消分享", Toast.LENGTH_LONG).show();
            intent.putExtra("share_status", false);
            intent.setAction("weibo share complete");
            mContext.sendBroadcast(intent);
            break;
        case WBConstants.ErrorCode.ERR_FAIL:
            Toast.makeText(mContext,
                    "分享失败" + "Error Message: " + baseResp.errMsg,
                    Toast.LENGTH_LONG).show();
            intent.putExtra("share_status", false);
            intent.setAction("weibo share complete");
            mContext.sendBroadcast(intent);
            break;
        }
    }

    private void handleShare(JSONArray data) {
        this.mPopShareWindow = new PopShareWindow(mWindowHandler, mContext,
                null, null, data);
        mPopupWindow = this.mPopShareWindow.getPopupWindow();
        if (mPopupWindow != null && mPopupWindow.isShowing()) {
            mPopupWindow.dismiss();// 关闭
        } else {
            mPopupWindow.showAtLocation(this.getWindow().getDecorView(),
                    Gravity.CENTER, 0, 0);
        }
    }

    private Handler mPopupHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            mPopLoginWindow = new PopLoginWindow(mContext, mWindowHandler);
            mPopupWindow = mPopLoginWindow.getPopupWindow();
            if (mPopupWindow != null && mPopupWindow.isShowing()) {
                mPopupWindow.dismiss();// 关闭
            } else {
                mPopupWindow.showAtLocation(((Activity) mContext).getWindow()
                        .getDecorView(), Gravity.CENTER, 0, 0);
            }

        }
    };

    private void handleLogin() {
        mPopupHandler.postDelayed(null, 1000);
    }

    private void handlePay(JSONArray data) {
        this.mPopPayWindow = new PopPayWindow(mContext, mWindowHandler, data);
        mPopupWindow = this.mPopPayWindow.getPopupWindow();
        if (mPopupWindow != null && mPopupWindow.isShowing()) {
            mPopupWindow.dismiss();// 关闭
        } else {
            mPopupWindow.showAtLocation(this.getWindow().getDecorView(),
                    Gravity.CENTER, 0, 0);
        }
    }

    protected void getEgretGameUrl() {
        EgretGameInfoHttpRequest egretGameInfoHttpRequest = new EgretGameInfoHttpRequest(
                mContext, this);
        egretGameInfoHttpRequest.postRequest(mEntryInfoModel);
    }

    public IWeiboShareAPI getIWeiboShareAPI() {
        return mWeiboShareAPI;
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        setImmersiveMode();
    }

    private void setImmersiveMode() {
        getWindow().getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
    }

    @Override
    public void onDestroy() {
        if (restartBroadcastReceiver != null) {
            unregisterReceiver(restartBroadcastReceiver);
        }
        if (mEgretBroadcastReceiver != null) {
            unregisterReceiver(mEgretBroadcastReceiver);
        }
        if (reloadBroadcastReceiver != null) {
            unregisterReceiver(reloadBroadcastReceiver);
        }
        if(nowUrlBroadcastReceiver != null) {
            unregisterReceiver(nowUrlBroadcastReceiver);
        }
        super.onDestroy();
    }

}
